﻿using System;
using System.IO;
using System.Net;
using RestSharp;

namespace UpdateHYLiveShowConsole
{
    public class HttpRequestHelper
    {
        public static string PostRequest(string url, string parameters)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            request.AddParameter("application/json", parameters, ParameterType.RequestBody);
            var response = client.Execute(request);
            var content = response.Content;
            return content;
        }

        public static string DeleteRequest(string url, string parameters)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.DELETE);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            request.AddParameter("application/json", parameters, ParameterType.RequestBody);
            var response = client.Execute(request);
            var content = response.Content;
            return content;
        }

        public static string PutRequest(string url, string parameters)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.PUT);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            request.AddParameter("application/json", parameters, ParameterType.RequestBody);
            var response = client.Execute(request);
            var content = response.Content;
            return content;
        }

        public static string PostRequest(string url, object value)
        {
            return PostRequest(url, Utility.JsonWrapper.Encode(value));
        }

        public static string DeleteRequest(string url, object value)
        {
            return DeleteRequest(url, Utility.JsonWrapper.Encode(value));
        }

        public static string PutRequest(string url, object value)
        {
            return PutRequest(url, Utility.JsonWrapper.Encode(value));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static HttpResult<T> PostRequest<T>(string url, object value)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            var body = Utility.JsonWrapper.Encode(value);
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            var response = client.Execute(request);
            var content = response.Content;


            return new HttpResult<T>
            {
                StatusCode = response.StatusCode,
                Data = Utility.JsonWrapper.Decode<T>(content)
            };

        }

        public static IRestResponse GetRequest(string url, string parameters)
        {
            var client = new RestClient(url + "?" + parameters);
            var request = new RestRequest(Method.GET);
            request.AddHeader("cache-control", "no-cache");
            var response = client.Execute(request);
            return response;
        }

        public static string GetRequestStr(string url, string parameters)
        {
            IRestResponse response = GetRequest(url, parameters);
            var content = response.Content;
            return content;
        }

        public static bool HttpDownload(string url, string path)
        {
            string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
            System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
            string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
            if (System.IO.File.Exists(tempFile))
            {
                try
                {
                    System.IO.File.Delete(tempFile);    //存在则删除
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                
            }
            FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            try
            {
                
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    //stream.Write(bArr, 0, size);
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                //stream.Close();
                fs.Close();
                responseStream.Close();
                System.IO.File.Move(tempFile, path);
                return true;
            }
            catch (Exception ex)
            {
                fs.Close();
                Console.WriteLine("出错："+ ex.Message);
                if (ex.Message.Contains("404"))
                {
                    url = url.Substring(0, url.LastIndexOf('/'));
                    path = path.Substring(0, path.LastIndexOf('.')) + url.Substring(url.LastIndexOf('.'));
                }
                Console.WriteLine("重新尝试："+ path);
                if (url.Length < 10 || path.Length - path.LastIndexOf('.') < 6)
                    return false;
                HttpDownload(url, path);
                return false;
            }
        }
    }

    public class HttpResult<T>
    {
        public T Data { get; set; }
        public HttpStatusCode StatusCode { get; set; }

    }
}